// 引入mysql模块 相对路径
const sql = require('../model/config');
// 引入markdown-it模块，把markdown语法转换成html
var md = require('markdown-it')();
// 公共页面的请求数据
async function common(){
    let nav = await sql('select * from nav');
    let banner = await sql('select * from banner');
    let boutique = await sql(`select article_id,thumb,title,intro from article where sort_id = 1`);
    let free = await sql(`select article_id,thumb,title,intro from article where sort_id = 2`);
    return {nav,banner,boutique,free}   
}
// GET index page. 
exports.index = async function(req, res) { 
    let { nav,banner,boutique,free } = await common();
    boutique = boutique.slice(0,4);
    free = free.slice(0,12);
    if (req.session.user) {
      const { id } =  req.session.user;
      const data = await sql(`select nickname,avatar from user where id = ${ id }`);
      const { nickname,avatar } = data[0];
      res.render('index',{ title:'首页',nav,banner,nickname,avatar,isUser:false,boutique,free });
    }else{
      res.render('index',{ title:'首页',nav,banner,isUser:true,boutique,free });
    }   
}
// GET boutique page. 
exports.boutique = async function(req, res) {
    const { nav } = await common();      
    // 定义每页面渲染的总数
    const pageSize = 8;
    // 获取page的值，默认页码初始值为1
    const page = req.query.page || 1;    
    // 根据页面的不同获取不同的8条数据，默认第一次渲染 1-8 条
    const boutique = await sql(`select article_id,sort_id,thumb,title,intro from article where sort_id = 1 limit ${ (page-1)*pageSize },${pageSize}`);
    // 获取当前页面的分页按钮总数
    const boutiqueCount = await sql(`select * from article where sort_id = 1`);
    // 把数字类型转换成数组，方便前端遍历渲染
    const buttonCount = new Array(Math.ceil(boutiqueCount.length / pageSize)); 
    // 判断用户是否登录，如果没有登录，前去登录
    if (req.session.user) {
      const { id } =  req.session.user;
      const data = await sql(`select nickname,avatar from user where id = ${ id }`);
      const { nickname,avatar } = data[0];
      res.render('boutique',{ title:'精品',nav,nickname,avatar,isUser:false,boutique,buttonCount });
    }else{    
      // res.redirect('/');
      res.send("<script>alert('请先登录，访问页面...');location.href='/'</script>")
    }
    
}
// GET free page. 
exports.free = async function(req, res) {
    // 获取cookie
    console.log(req.cookies);
    console.log("==========cookie=========");
    console.log(req.cookies.username);
    let { nav } = await common();   
    // 定义每页面渲染的总数
    const pageSize = 8;
    // 获取page的值，默认页码初始值为1
    let page = req.query.page || 1;    
    // 根据页面的不同获取不同的8条数据，默认第一次渲染 1-8 条
    let free = await sql(`select article_id,sort_id,thumb,title,intro from article where sort_id = 2 limit ${ (page-1)*pageSize },${pageSize}`);
    // 获取当前页面的分页按钮总数
    let freeCount = await sql(`select * from article where sort_id = 2`);
    // 把数字类型转换成数组，方便前端遍历渲染
    let buttonCount = new Array(Math.ceil(freeCount.length / pageSize));    
    // 判断
    if (req.session.user) {
        var { id } =  req.session.user;
        var data = await sql(`select nickname,avatar from user where id = ${ id }`);
        var { nickname,avatar } = data[0];
        res.render('free',{title:'免费',nav,nickname,avatar,isUser:false,free,buttonCount });    
    }else{
        res.render('free',{title:'免费',nav,isUser:true,free,buttonCount });
    }
}
// GET detail page. 
exports.detail = async function(req, res) {
    // query  传参  /detail?id=1&name="zhangsan"
    // console.log("文章详情===》",req.query);
    // params 传参 /detail/1/zhangsan   路由接收的形式 /detail/:id/:name
    // console.log("文章详情===》",req.params);

    const { nav } = await common();
    // 查找对应的文章内容
    const article_id = Number(req.query.id);
    let article = await sql(`select * from article where article_id = ${article_id} `);
    // 阅读量，每一次进来的时候 hits 阅读量++
    let hits = article[0].hits || 0;
    hits++;
    await sql(`update article set hits = ? where article_id = ${article_id} `,[hits]);
    article = await sql(`select * from article where article_id = ${article_id} `);
    // 转换成对象形式
    article = article[0];
    // var result = md.render('# markdown-it rulezz!');
    article.content = md.render(article.content);

    // 判断
    if (req.session.user) {
      const { id } =  req.session.user;
      const data = await sql(`select nickname,avatar from user where id = ${ id }`);
      const { nickname,avatar } = data[0];   
      // 判断当前文章是否点赞了
      let thumbsUp = await sql(`select on_off from thumbs_up where nickname = ? and article_id = ?`,[nickname,article_id]);
      let onOff
      if (thumbsUp.length !== 0) {
        onOff = thumbsUp[0].on_off;
      }      
      res.render('detail',{ title:'详情', nav, nickname, avatar, isUser:false, article, onOff });
    }else{
      res.render('detail',{ title:'详情', nav, isUser:true, article });
    } 
}
// GET search page. 
exports.search = async function(req, res) {
    const { nav } = await common(); 
    // 搜索的关键字
    const s = req.query.s;
    // 查找对应的文章 -- 模糊查询  --- 过滤掉 % 和 _ 通配符
    const search = await sql(`select * from article where content like "% \\${ s }%"`);
    // var search = await sql(`select * from article where content like "%\${ s }%" escape "\"`);
    // 定义每页面渲染的总数
    const pageSize = 8;
    // 获取当前页面的分页按钮数量,把数字类型转换成数组，方便前端遍历渲染
    let buttonCount = new Array(Math.ceil(search.length / pageSize));
    if (req.session.user) {
        const { id } =  req.session.user;
        const data = await sql(`select nickname,avatar from user where id = ${ id }`);
        const { nickname,avatar } = data[0];
        res.render('search',{ title:'搜索', nav, nickname, avatar, isUser:false, search, buttonCount });    
    }else{
        res.render('search',{ title:'搜索', nav, isUser:true, search, buttonCount });
    }  
}
// GET user page. 
exports.user = async function(req, res) {
    const { nav } = await common(); 
    // 判断
    if(req.session.user){
      const { id,username } =  req.session.user;
      const data = await sql(`select nickname,avatar from user where id = ${ id }`);
      const { nickname,avatar } = data[0];
      res.render('user',{ title:'用户设置', nav, nickname, avatar, isUser:false, username });
    }else{
      res.render('user',{ title:'用户设置', nav, isUser:true });
    }
}

// GET article page.
exports.article = async function(req, res) {
  const { nav } = await common(); 
  // 判断
  if(req.session.user){
    const { id,username } =  req.session.user;
    const data = await sql(`select nickname,avatar from user where id = ${ id }`);
    const { nickname,avatar } = data[0];
    res.render('article',{ title:'发文章', nav, nickname, avatar, isUser:false, username });
  }else{
    res.render('article',{ title:'发文章', nav, isUser:true });
  }
}